####====####



#encoding:UTF-8

"""
赢损组合策略 2022(R) 余超  xa87@live.cn
"""
ePocket_ver=1.5						#版本	,	修改：	onUpdate
ePocket_Parent="$ePocket_Parent$"	#运行父对象

#模板
from pickle import FALSE, NONE, TRUE
from ctaTemplate import *
from ctaBase import *
#系统
import datetime
import math
import socket
import _thread
import time

'''
CTAORDER_BUY = u'买开'
CTAORDER_SELL = u'卖平'
CTAORDER_SELL_TODAY = u'卖平今'
CTAORDER_SHORT = u'卖开'
CTAORDER_COVER = u'买平'
CTAORDER_COVER_TODAY = u'买平今'


'''
def udp_thread(parent):
	'''APP指令触发'''
	while True:
		try:
			if parent.exit==TRUE:
				return
			if parent.udp!=None:
				dat,ip=parent.udp.recvfrom(100)
				if dat!=None:
					parent.output("收到指令:"+dat.decode())
					msg=dat.decode().split(',')
					cmd=msg[0]
					data=msg[1].split('/')
					if len(msg)==2 :
						if cmd=="test":
							#parent.udp.sendto(f"@test,{data[0]},{ePocket_ver},{ePocket_Parent}".encode('utf-8'),("127.0.0.1",1988))
							parent.msg_send(f"@test,{data[0]},{ePocket_ver},{ePocket_Parent}".encode('utf-8'))
							parent.output(f"测试成功:{data[0]}")
						elif cmd=="exec":
							try:
								parent.output("exec运行:"+data[0])
								exec(data[0])
							except:
								parent.output("exec错误:"+sys.exc_info())
						elif cmd=="store":
							#获取持仓情况
							user=parent.get_investor()
							money=parent.getInvestorPosition(user)
							parent.msg_send(f"@store,{money}".encode('utf-8'))
						elif cmd=="cancel":
							parent.output(f"开始撤单:{data[0]}")
							parent.cancelOrder(int(data[0]))
							#parent.output(f"撤单成功:{data[0]},{r}")
							parent.msg_send(f"@cancel,{data[0]}".encode('utf-8'))
						elif cmd=="bind":
							#bind,vtSymbol, exchange
							parent.msg_send("@bind,ok".encode('utf-8'))
							parent.vtSymbol=data[0]
							parent.exchange=data[1]
							#parent.subSymbol()		#订阅更新
							#parent.onStart()
							#parent.setParam()		#刷新参数
							parent.unSubSymbol()	#取消订阅
							parent.onUpdate({})		#刷新策略
							parent.subSymbol()
							parent.output("绑定完成:"+msg[0])
						elif cmd=="exchange":
							#$"exchange,{(int)exc}/{point}/{count}/{deal.symbol.Code}/{deal.symbol.Company}";
							#点数，数量，代码，期货所
							#收到指令:exchange,1/11996/1/p2209/DCE
							if len(data)==5:
								deal=data[0];
								f1=float(data[1])	#point
								f2=int(data[2])		#count
								st='无'
								if deal=="1":
									#CTAORDER_BUY 买开
									#self.sendOrder(CTAORDER_BUY,point,self.argBuyCount,sy,ex)
									st=CTAORDER_BUY
								elif deal=="2":
									#CTAORDER_SELL 卖平
									st=CTAORDER_SELL
								elif deal=="3":
									#CTAORDER_SELL_TODAY 卖平今
									st=CTAORDER_SELL_TODAY
								elif deal=="4":
									#CTAORDER_SHORT 卖开
									st=CTAORDER_SHORT
								elif deal=="5":
									#CTAORDER_COVER 买平
									st=CTAORDER_COVER
								elif deal=="6":
									#CTAORDER_COVER_TODAY 买平今
									st=CTAORDER_COVER_TODAY
								else:
									parent.output("错误指令:"+str(cmd))
									continue
								r=parent.sendOrder(st,f1,f2,data[3],data[4])
								if r==NONE:
									r=""
								msg=f"@exchange,{r},{data[3]}.{data[4]}"
								parent.msg_send(msg.encode('utf-8'))
								parent.output("交易结果："+msg)
							else:
								parent.output("错误长度 / :"+str(len(data)))
						else:
							parent.output("未知指令 / :"+str(cmd))

			else:
				time.sleep(0.01)
		except ConnectionResetError:
			pass
		except:
			parent.output(sys.exc_info())
			time.sleep(1)

#自定义
	
class ePocket(CtaTemplate):
	"""
	赢损组合策略 2022 V1.5
	"""
	className = u'ePocket'
	author = u'余超'

	#参数列表
	paramList = [ 'test']

	 # 参数映射表
	paramMap = { 'test':u'参数请在ePocket中设置'}
	# 变量列表
	varList = ['Last', 'vTime']
	# 变量映射表
	varMap = {'Last': u'状态', 'vTime': u'实时'}

	#自定义变量
	
	#当天状态
	Last="none"	#最后状态 none=无 buy=开多 short=开空
	Index=0

	#通信
	udp=None
	exit=FALSE
	#udp发送函数，发往1988,1989端口，同时发送
	def msg_send(self,msg):
		self.udp.sendto(msg,("127.0.0.1",1988))
		self.udp.sendto(msg,("127.0.0.1",1989))
	#初始化函数
	def __init__(self, ctaEngine=None, setting={}):
		super(ePocket, self).__init__(ctaEngine, setting)
		self.output("*初始化策略中")
		#初始化变量
		self.vTime="Wait"
		self.test=0
		self.vtSymbol=""
		self.exchange=""
		#模板变量
		self.is_on_time = False
		self.trigger_time = '15:01:00'
		self.sell_price = 0.0
		self.volume = 1
		self.buy_price = 0.0
		# 修改此开关时首字母一定要大写
		self.time = datetime.datetime.now().strftime('%Y - %m - %d %H:%M:%S')
		# 用来标识是否已买开和卖开，避免重复发单
		self.has_buy = False
		self.has_sell = False
		#初始化网络
		self.udp=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
		self.udp.bind(("127.0.0.1",1987))
		_thread.start_new_thread(udp_thread,(self,))

	def onTick(self, tick):
		super(ePocket, self).onTick(tick)
		#tick数据
		ud=f"@tick,point={tick.lastPrice},datetime={tick.datetime},lastVolume={tick.lastVolume},volume={tick.volume},openInterest={tick.openInterest},"
		#当日行情
		ud+=f"openPrice={tick.openPrice},highPrice={tick.highPrice},lowPrice={tick.lowPrice},preClosePrice={tick.preClosePrice},upperLimit={tick.upperLimit},lowerLimit={tick.lowerLimit},turnover={tick.turnover},"
		#合约数据
		ud+=f"symbol={tick.vtSymbol},exchange={tick.exchange},"
		#五档信息
		ud+=f"bidPrice={tick.bidPrice1}/{tick.bidPrice2}/{tick.bidPrice3}/{tick.bidPrice4}/{tick.bidPrice5},"
		ud+=f"askPrice={tick.askPrice1}/{tick.askPrice2}/{tick.askPrice3}/{tick.askPrice4}/{tick.askPrice5},"
		ud+=f"bidVolume={tick.bidVolume1}/{tick.bidVolume2}/{tick.bidVolume3}/{tick.bidVolume4}/{tick.bidVolume5},"
		ud+=f"askVolume={tick.askVolume1}/{tick.askVolume2}/{tick.askVolume3}/{tick.askVolume4}/{tick.askVolume5}"
		#ud+=f"gatewayName={self.gatewayName()},rawData={self.rawData()}"
		#self.udp.sendto(ud.encode('utf-8'),("127.0.0.1",1988))
		self.msg_send(ud.encode('utf-8'));
		self.Index+=1

		#局部变量
		point=tick.lastPrice
		#显示实时信息
		self.vTime=str(self.Index) + "/" + str(point) +" " + tick.time+ " "+f"{tick.vtSymbol}.{tick.exchange}";
		self.putEvent()


	def onBar(self, bar):
		"""收到Bar推送（必须由用户继承实现）"""
		# super(ePocket, self).onBar(bar)
		self.output("*Bar触发")
		#self.output("%d %d"%(bar.open,bar.close))

	def get_indicator(self):
		self.output("*get_indicator触发")
		self.trigger_price = self.trigger_open * (1 + self.preset_rise / 100.0)

	def get_signal(self, tick):
		self.output("*get_signal触发")

	def exec_signal(self, tick):
		self.output("*exec_signal触发")

	def onTrade(self, trade, log=True):
		super(ePocket, self).onTrade(trade, log)
		m=f"@trade,name={trade.symbol}.{trade.exchange},tradeID={trade.tradeID},orderID={trade.orderID},direction={trade.direction},offset={trade.offset},price={trade.price},volume={trade.volume},tradeTime={trade.tradeTime},commission={trade.commission}"
		#self.udp.sendto(m.encode('utf-8'),("127.0.0.1",1988))
		self.msg_send(m.encode('utf-8'))
		self.output(f"交易：{m}")
	def onOrder(self, order, log=True):
		super(ePocket, self).onOrder(order, log)
		m=f"@order,name={order.symbol}.{order.exchange},orderID={order.orderID},direction={order.direction},price={order.price},totalVolume={order.totalVolume},tradedVolume={order.tradedVolume},status={order.status}"
		#,sessionID={order.sessionID},frontID={order.frontID}
		#self.udp.sendto(m.encode('utf-8'),("127.0.0.1",1988))
		self.msg_send(m.encode('utf-8'))
		self.output(f"订单：{m}")

	def onStart(self):
		super(ePocket, self).onStart()
		self.output(f"*已开始 合约：%s@%s"%(self.vtSymbol,self.exchange))

	def onStop(self):
		self.udp.close()
		self.exit=TRUE
		self.output(f"* 已停止脚本")
		super(ePocket, self).onStop()

	def onErr(self, error):
		if 'orderID' in error:
			oid = error['orderID']
			self.output("执行错误：oid="+str(oid))




####====####